﻿using Frameworks;
using System;
using System.Collections.Generic;

namespace DotNetClient
{
    public class CallbackFactory : Singleton<CallbackFactory>
    {
        private CallbackFactory() { }

        public override void OnSingletonInit()
        {
            base.OnSingletonInit();
            _callbacks = new Dictionary<string, Action<Message>>();
        }

        public override void Dispose()
        {
            base.Dispose();
            _callbacks.Clear();
        }

        public Dictionary<string, Action<Message>> Callbacks => _callbacks;
        private Dictionary<string, Action<Message>> _callbacks;

        /// <summary>
        /// 注册 回调
        /// </summary>
        public void RegistCallbacks()
        {
            //registCallback(Routes.C2S_GATE_CONNECT, GameHandler.onResConnect); // no listen
            // connector
            registCallback(Routes.C2S_CONNECTOR_LOGIN, GameHandler.onResLogin);
            registCallback(Routes.C2S_CONNECTOR_LOGOUT, GameHandler.onResLogout);
            registCallback(Routes.C2S_CONNECTOR_REGISTER, GameHandler.onResRegister);
            // lobby
            registCallback(Routes.C2S_LOBBY_MATCH, GameHandler.onResMatch);
            //registCallback(Routes.C2S_LOBBY_UNMATCH, GameHandler.onResUnmatch);
            //registCallback(Routes.C2S_LOBBY_SEND_CHAT, GameHandler.onResSendChat); // no res
            // room
            registCallback(Routes.C2S_ROOM_CREATE, GameHandler.onResRoomCreate);
            registCallback(Routes.C2S_ROOM_JOIN, GameHandler.onResRoomJoin);
            registCallback(Routes.C2S_ROOM_LEAVE, GameHandler.onResRoomLeave);
            //registCallback(Routes.C2S_ROOM_PLAYER_ACTION, GameHandler.onResPlayerAction); // no res
            // database
            registCallback(Routes.C2S_DB_GET_USER, GameHandler.onResGetUser);
            registCallback(Routes.C2S_DB_RENAME, GameHandler.onResRename);
            registCallback(Routes.C2S_DB_GET_DOUDIZHU_INFO, GameHandler.onResGetDoudizhuInfo);
        }

        private void registCallback(string route, Action<Message> handler)
        {
            if (_callbacks.ContainsKey(route))
            {
                // 已注册过同名的
                UnityEngine.Debug.LogError("already exist route: " + route);
                return;
            }
            _callbacks.Add(route, handler);
        }

        /// <summary>
        /// 执行 回调
        /// </summary>
        /// <param name="route"></param>
        /// <param name="data"></param>
        public void InvokeHandle(string route, Message data)
        {
            Action<Message> handler;
            _callbacks.TryGetValue(route, out handler);
            if (handler != null)
            {
                handler(data);
            }
            else
            {
                UnityEngine.Debug.LogWarning("cannot find handler for " + route);
            }
        }
    }
}
